package com.webserver.http;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 此类包含所有HTTP协议相关内容
 */
public class HttpContext {
    //保存所有Content-Type的值与资源后缀的对应关系
    private static Map<String,String>mimeMapping=new HashMap<>();
    static {
        try {
            initMineMapping();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
    private static void initMineMapping()throws DocumentException {
        SAXReader reader=new SAXReader();
        Document readerDocument=reader.read("./config/web.xml");
        Element root=readerDocument.getRootElement();
        List<Element>list=root.elements("mime-mapping");
        for (Element element : list) {
            String key=element.elementText("extension");
            String value=element.elementText("mime-type");
            mimeMapping.put(key,value);
        }
    }

    /**
     * 根据给定资源后缀名获取对应的Content-Type的值
     * @param ext
     * @return
     */
    public static String getMimeType(String ext){
        return mimeMapping.get(ext);
    }

    public static void main(String[] args) {
        System.out.println(getMimeType("js").length());
    }
}